/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.system.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.boot.domain.dto.MessageDTO;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.enums.OperateTypeEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.system.IpBlackListDTO;
import com.iwindplus.mgt.domain.dto.system.IpBlackListSearchDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.vo.system.IpBlackListPageVO;
import com.iwindplus.mgt.domain.vo.system.IpBlackListVO;
import com.iwindplus.mgt.server.mapper.system.IpBlackListMapper;
import com.iwindplus.mgt.server.model.system.IpBlackListDO;
import com.iwindplus.mgt.server.service.system.IpBlackListService;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * IP黑名单业务层接口实现类.
 *
 * @author zengdegui
 * @since 2020/3/25
 */
@Slf4j
@Service
@CacheConfig(cacheNames = {"ipBlackList"})
@Transactional(rollbackFor = Exception.class)
public class IpBlackListServiceImpl extends JoinCrudRepository<IpBlackListMapper, IpBlackListDO> implements IpBlackListService {

    @Resource
    private RedissonClient redissonClient;

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(IpBlackListDTO entity) {
        this.getIpIsExist(entity.getIp().trim());
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setSeq(this.getNextSeq());
        IpBlackListDO model = BeanUtil.copyProperties(entity, IpBlackListDO.class);
        super.save(model);
        entity.setId(model.getId());
        this.sendMsg(OperateTypeEnum.ADD);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<IpBlackListDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        super.removeByIds(ids);
        this.sendMsg(OperateTypeEnum.DELETE);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean edit(IpBlackListDTO entity) {
        IpBlackListDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (CharSequenceUtil.isNotBlank(entity.getIp()) && !CharSequenceUtil.equals(data.getIp(), entity.getIp().trim())) {
            this.getIpIsExist(entity.getIp().trim());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        IpBlackListDO model = BeanUtil.copyProperties(entity, IpBlackListDO.class);
        super.updateById(model);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        IpBlackListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        IpBlackListDO entity = new IpBlackListDO();
        entity.setId(id);
        entity.setStatus(status);
        entity.setVersion(data.getVersion());
        super.updateById(entity);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        IpBlackListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        IpBlackListDO param = new IpBlackListDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        this.sendMsg(OperateTypeEnum.MODIFY);
        return Boolean.TRUE;
    }

    @Override
    public IPage<IpBlackListPageVO> page(IpBlackListSearchDTO entity) {
        PageDTO<IpBlackListDO> page = new PageDTO<>(entity.getCurrent(), entity.getSize());
        page.setOptimizeCountSql(Boolean.FALSE);
        page.setOptimizeJoinOfCountSql(Boolean.FALSE);
        LambdaQueryWrapper<IpBlackListDO> queryWrapper = Wrappers.lambdaQuery(IpBlackListDO.class)
            .orderByDesc(IpBlackListDO::getModifiedTime);
        if (Objects.nonNull(entity.getStatus())) {
            queryWrapper.eq(IpBlackListDO::getStatus, entity.getStatus());
        }
        if (CharSequenceUtil.isNotBlank(entity.getIp())) {
            queryWrapper.like(IpBlackListDO::getIp, entity.getIp().trim());
        }
        final PageDTO<IpBlackListDO> modelPage = super.page(page, queryWrapper);
        return modelPage.convert(model -> BeanUtil.copyProperties(model, IpBlackListPageVO.class));
    }

    @Cacheable(key = "#root.methodName", unless = "#result == null")
    @Override
    public List<String> listIp() {
        LambdaQueryWrapper<IpBlackListDO> queryWrapper = Wrappers.lambdaQuery(IpBlackListDO.class)
            .eq(IpBlackListDO::getStatus, EnableStatusEnum.ENABLE)
            .select(IpBlackListDO::getIp)
            .orderByAsc(List.of(IpBlackListDO::getIp));
        List<IpBlackListDO> list = super.list(queryWrapper);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return list.stream().map(IpBlackListDO::getIp).distinct().collect(Collectors.toCollection(ArrayList::new));
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public IpBlackListVO getDetail(Long id) {
        IpBlackListDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        IpBlackListVO result = BeanUtil.copyProperties(data, IpBlackListVO.class);
        return result;
    }

    private void getIpIsExist(String ip) {
        QueryWrapper<IpBlackListDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(IpBlackListDO::getIp, ip);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.IP_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @return Integer
     */
    private Integer getNextSeq() {
        QueryWrapper<IpBlackListDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private void sendMsg(OperateTypeEnum operateType) {
        try {
            final MessageDTO messageDTO = new MessageDTO();
            messageDTO.setOperateType(operateType);
            final RTopic rTopic = this.redissonClient.getTopic(MgtConstant.TOPIC_IP_BLACK_LIST);
            rTopic.publishAsync(messageDTO);
            log.info("发送redis IP黑名单 topic 成功={}", messageDTO);
        } catch (Exception ex) {
            log.error("redis IP黑名单 topic Exception={}", ex);
        }
    }
}
